package com.mimiwang.email.controller;

import com.mimiwang.common.entity.email.Email;
import com.mimiwang.common.utils.RandomCodeUtil;
import com.mimiwang.common.utils.ResponseUtil;
import com.mimiwang.email.constant.RedisConstant;
import com.mimiwang.email.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import java.util.concurrent.TimeUnit;


/**
 * @AUTHOR:游李滨
 * @DATE:2023/4/28 13:00
 */
@RestController
@Slf4j
public class EmailController {


    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    EmailService emailService;


    @PostMapping("/email/html")
    String sendHtmlEmail(@RequestBody Email email){
        try {
            emailService.sendHtmlMail(email.getTo(),email.getSubject(),email.getContent(),email.getSubject());
            return ResponseUtil.successJSONData("发送成功");
        } catch (MessagingException e) {
            return ResponseUtil.errorJSONData("发送失败");
        }
    }

    @GetMapping("/email/html/code")
    String sendRandomCodeEmail(String to){
//        redisKey
        String key= RedisConstant.LOGIN_EMAIL_CODE_KEY+":" +to;

        Boolean hasKey = redisTemplate.hasKey(key);
        if(hasKey != null && hasKey){

//            如果存在，则不生成
            return ResponseUtil.successJSONData("发送成功");
        }

        String code=RandomCodeUtil.generateRandomCode(6);
        Email email = new Email();
        email.setTo(to);

        email.setSubject("验证码");
        email.setContent("您好！，感谢支持MimiWang。您的验证码为："+"<h2 style='color:red'>"+code+"</h2>"+"千万不能告诉别人哦！");
        try {

            emailService.sendHtmlMail(email.getTo(),email.getSubject(),email.getContent(),email.getCc());

            redisTemplate.opsForValue().set(key,code,3, TimeUnit.MINUTES);
            log.info("key:"+code);
            return ResponseUtil.successJSONData("发送成功");
        } catch (MessagingException e) {
            return ResponseUtil.errorJSONData("发送失败");
        }
    }
}
